<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] &raquo; ".__("Member Point Management");
$page_title=__("Member Point Management");

if(!$pv["task"]["Member Point"]){
 $errmsg="<h2>$page_title</h2>".format_err(__("You do not have the privilege to manage member point."));
            
 print format_admin_page($errmsg, $this_title);
 exit();
}

$r_point=array("ewallet","eswallet","cwallet","mwallet","swallet","owallet");
$r_point_d=array("ewallet"=>__($vars["ewallet_title"]), "eswallet"=>__($vars["eswallet_title"]), "cwallet"=>__($vars["cwallet_title"]), "mwallet"=>__($vars["mwallet_title"]), "swallet"=>__($vars["swallet_title"]), "owallet"=>__($vars["owallet_title"]));
$r_transaction=array("credit","debit");
$r_transaction_d=array("credit"=>__("Credit"),"debit"=>__("Debit"));$r_currency=array("HKD","IND","INR","JYP","MYR","RMB","SGD","THB","TWD","USD");$r_currency_d=array("HKD"=>"HKD","IND"=>"IND","INR"=>"INR","JYP"=>"JYP","MYR"=>"MYR","RMB"=>"RMB","SGD"=>"SGD","THB"=>"THB","TWD"=>"TWD","USD"=>"USD");
$td_width=130;

//#####AJAX CALL#####
if($_GET["aj"] && $_GET["check_uid"]){
	$ajresult = ajax_check_user($post_d['uid']);
	if($ajresult['status'] == 3){
		$ajmsg = "The Member ID '$post_s[uid]' could not be found.";
	}elseif($ajresult['status'] == 2){
		$ajmsg = "The Member ID '$post_s[uid]' could not be found.";
	}elseif($ajresult['status'] == 1){
		$ajmsg = "Member ID '$post_s[uid]', name: {$ajresult['user_detail']['name']}"."<br />\n<br />\n".__($vars['ewallet_title']).__(":")." ".number_format($ajresult['user_detail']["ewallet"], 2)."<br />".__($vars['eswallet_title']).__(":")." ".number_format($ajresult['user_detail']["eswallet"], 2)."<br />".__($vars['cwallet_title']).__(":")." ".number_format($ajresult['user_detail']["cwallet"], 2)."<br />".__($vars['mwallet_title']).__(":")." ".number_format($ajresult['user_detail']["mwallet"], 2)."<br />".__($vars['swallet_title']).__(":")." ".number_format($ajresult['user_detail']["swallet"], 2)."<br />".__($vars['owallet_title']).__(":")." ".number_format($ajresult['user_detail']["owallet"], 2)."<br />".__('Daily Balance').__(":")." ".number_format($ajresult['user_detail']["dividend_balance"], 2);
	}
	$status = $ajresult['status'];

	print format_xml(array('status'=>$status, 'msg'=>$ajmsg));
	exit;
}
//#####END AJAX CALL#####

//#####MEMBER POINT TRANSACTION POST
if($_POST["__req"]){
 //#####ERROR CHECK
 if(!$r_user=get_user_detail_by_id($post_d["uid"])){
  $errmsg.=__("Invalid Member ID.")."<br />\n";
 }
 if(!in_array($post_s["point"], $r_point)){
  $errmsg.=__("Invalid Point Type.")."<br />\n";
 }
 if(!in_array($post_s["transaction"], $r_transaction)){
  $errmsg.=__("Invalid Transaction.")."<br />\n";
 }
 if(!$post_s["amount"] || !is_numeric($post_s["amount"]) || $post_s["amount"]<=0){
  $errmsg.=__("Amount must be digits with value more than 0.")."<br />\n";
 } /*allow to have negetive balance elseif($post_s["transaction"]=="debit"){
  if($post_s["amount"]>$r_user[$post_s["point"]]){
   $errmsg.=replace_tag(__("The Member ID: '<%uid%>' does not have sufficient <%point%> for this transaction."), array("<%uid%>"=>$post_h['uid'], "<%point%>"=>$r_point_d[$post_s["point"]]))."<br />\n";
  }
 }*/
 if(!strlen($post_s["descr"])){
  $errmsg.=__("Please provide a description for this transaction.")."<br />\n";
 }

 //record transaction
 if(!$errmsg){
  $datetime=ndate($vars["system_date_format"]);
  $sql="update $db->users set $post_s[point]=$post_s[point]".($post_s["transaction"]=="credit"? "+" : "-")."$post_s[amount] where id='$post_d[uid]' limit 1";
  if(!mysql_query($sql)){
   $errmsg.=__("Error performing the transaction. No transaction has been in place.")."<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
   $critical_error.=$errmsg;
  }else{
   if(!mysql_query($sql2="insert into ".$vars["dbi"]["prefix"]."member_$post_s[point]_record (uid, aid, type, amount, descr, cdate) values ('$post_d[uid]', '$aid', '$post_d[transaction]', '$post_d[amount]', '$post_d[descr]', '$datetime')")){
    $errmsg.=replace_tag(__("The transaction has been performed and the Member ID: <%uid%> has been <%trans%> with <%x%> <%point%>, but the transaction record could not be recorded."), array("<%uid%>"=>$post_h['uid'], "<%trans%>"=>__("$post_s[transaction]ed"), "<%x%>"=>number_format($post_s["amount"], 2), "<%point%>"=>$r_point_d[$post_s["point"]]))." ".
    __("Please manually insert this record by executing SQL:")."<br />\n<br />\n$sql2<br />\n<br />\nError: ".mysql_error()."<br />\n";
    $critical_error.=$errmsg;
   }else{
		$new_eid = mysql_insert_id();
		$last_bal = @mysql_result(mysql_query("select bal from {$vars["dbi"]["prefix"]}member_$post_s[point]_record where uid='$post_d[uid]' and id!=$new_eid order by id desc limit 1"), 0);
		if(!$last_bal){
			$last_bal = 0;
		}
		if($post_s['transaction'] == 'credit'){
			$last_bal += $post_s['amount'];
		}else{
			$last_bal -= $post_s['amount'];
		}
		@mysql_query("update {$vars["dbi"]["prefix"]}member_$post_s[point]_record set bal='$last_bal' where id='$new_eid' limit 1");				if($post_s['point']=='eswallet'){			@mysql_query("insert into {$vars["dbi"]["prefix"]}bank_transaction (currency,amount,code,eswallet,bankin_status,bdate,cdate,create_by,approve_by,remark2,status) values('$post_d[currency]','$post_d[amount_in]','$post_d[code]','$post_d[amount]','pending','$post_d[bdate]','$datetime','$_SESSION[aname]','$_SESSION[aname]','$post_d[descr]','approved')");		}
   }
   $logstr="Member ID: '$post_s[uid]', Name: $r_user[name] has been $post_s[transaction]ed with ".number_format($post_s["amount"], 2)." ".$r_point_d[$post_s["point"]].".";
  }
 }
 if(!$errmsg){
  $msg=replace_tag(__("The Member ID: '<%uid%>', Name: <%name%> has been successfully <%trans%> with <%x%> <%point%>."), array("<%uid%>"=>$post_h['uid'], "<%name%>"=>$r_user['name'], "<%trans%>"=>__("$post_s[transaction]ed"), "<%x%>"=>number_format($post_s["amount"], 2), "<%point%>"=>$r_point_d[$post_s["point"]])).
  "<br />\n<br />\n".__("Description").__(":")." $post_s[descr]<br />\n";
 }

 $errmsg=$errmsg? format_err($errmsg) : "";
 $msg=$msg? format_msg($msg) : "";
}
//#####END MEMBER POINT TRANSACTION POST

$point_select=build_select($r_point, $r_point_d, $post_s["point"], "point", $inputbox_style);
$transaction_select=build_select($r_transaction, $r_transaction_d, $post_s["transaction"], "transaction", $inputbox_style);$currency_select=build_select($r_currency, $r_currency_d, $post_s["currency"], "currency", $inputbox_style);
?><script type='text/javascript' src='<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("fn/fn_number_format.js,common.js,jquery.js,jquery.livequery.js"); ?>'></script><script type='text/javascript'>jQuery(document).ready(function(j){	j('form[@name=member_point_form]').submit(function(){		var confirm_text='<?php echo AddSlashes(__("<#a#> GBP<#b#> <#c#> points to Member ID <#d#>.")); ?>\n\n<?php echo AddSlashes(__("Are you sure?")); ?>';		confirm_text=confirm_text.replace(/\<#a#\>/, j('select[@name=transaction]').val());		confirm_text=confirm_text.replace(/\<#b#\>/, j('input[@name=amount]').val());		confirm_text=confirm_text.replace(/\<#c#\>/, j('select[@name=point]').val());		confirm_text=confirm_text.replace(/\<#d#\>/, j('input[@name=uid]').val());		if(confirm(confirm_text)){ $("#multiple").val()			j('input[@name=submit_btn]').attr('disabled','disabled');		}else{			return false;		}	});});</script><script type='text/javascript' src='<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js,jquery.datepicker.js"); ?>'></script><script type='text/javascript'>jQuery(document).ready(function(j){	<?php #datepicker ?>	j('#bdate').datepicker({		changeMonth: true,		changeYear: true,		dateFormat: 'yy-mm-dd',		minDate: new Date(2009,5,1), 		maxDate: '+1M +10D'	});});</script><link rel="stylesheet" href="<?php echo CSS_URL; ?>/jstheme/ui-lightness/jquery-ui.css" type="text/css" /><?php
//member point
if($post_s["uid"] && $user=get_user_detail_by_id($post_d["uid"])){
 $user_text=replace_tag(__("Member ID: <%uid%>, Name: <%name%>"), array("<%uid%>"=>$post_h['uid'], "<%name%>"=>$user['name']))."<br />\n<br />\n".__($vars['ewallet_title']).__(":")." ".number_format($user["ewallet"], 2)."<br />\n".__($vars['eswallet_title']).__(":")." ".number_format($user["eswallet"], 2)."<br />".__($vars['cwallet_title']).__(":")." ".number_format($user["cwallet"], 2)."<br />".__($vars['mwallet_title']).__(":")." ".number_format($user["mwallet"], 2)."<br />".__($vars['swallet_title']).__(":")." ".number_format($user["swallet"], 2)."<br />\n".__($vars['owallet_title']).__(":")." ".number_format($user["owallet"], 2)."<br />".__('Daily Balance').__(":")." ".number_format($user["dividend_balance"], 2);
}

//javascript
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("common.js,jquery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 j('form[@name=member_point_form]').submit(function(){
  j('input[@name=submit_btn]').attr('disabled','disabled');
 });

 j('input#check_user_btn').click(function(){
  j('div#user_text').html('').removeClass('red');
  if(j('input[@name=uid]').val()==''){
   j('div#user_text').html('".AddSlashes(__("Please provide a Member ID!"))."').addClass('red');
  }else{
   j(this).attr('disabled','disabled');
   j.ajax({
    url: '$this_file?aj=1&check_uid=1',
    data: {'uid': j('input[@name=uid]').val()},
    type: 'post',
    dataType: 'xml',
    error: function(){
     j('div#user_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');
    },
    success: function(data){
     var mesg='';
     if(j('loggedout', data).text()=='loggedout'){
      mesg='".AddSlashes(__("You have been logged out."))."';
     }else{
      j(data).find('msg').each(function(){
       mesg+=j(this).text()+'<br />';
      });
     }
     var status=j(data).find('status').text();
     j('div#user_text').html(mesg).addClass(status==1? 'bold' : 'red');
    },
    complete: function(){
     j('input#check_user_btn').attr('disabled','');
    }
   });
  }
 });
});
</script>";

$member_point=($errmsg || $msg? $errmsg.$msg : "").
"<form name='member_point_form' method='post' action='$this_file'>
<input type='hidden' name='__req' value='1' />
<table class='amt_table'>
 <tr>
  <td width='$td_width'>".__("Member ID").__(":")." ".__("*")."</td>
  <td><input type='text' name='uid' class='inputbox' style='width:300px;' value=\"$post_h[uid]\" />
      <input type='button' id='check_user_btn' value=\"".__("Check User")."\" />
      <div id='user_text'>$user_text</div></td>
 </tr>
 <tr>
  <td>".__("Point Type").__(":")." ".__("*")."</td>
  <td>$point_select</td>
 </tr>
 <tr>
  <td>".__("Transaction").__(":")." ".__("*")."</td>
  <td>$transaction_select</td>
 </tr>
 <tr>
  <td>".__("Amount").__(":")." ".__("*")."</td>
  <td><input type='text' name='amount' $inputbox_style value=\"$post_h[amount]\" /></td>
 </tr>
 <tr>
  <td>".__("Description").__(":")." ".__("*")."</td>
  <td><textarea name='descr' rows='6' $inputbox_style>$post_h[descr]</textarea></td>
 </tr> <tr>  <td>".__("Bank In Date").__(":")." ".__("*")."</td>  <td><input type='text' name='bdate' $inputbox_style /></td> </tr> <tr>  <td>".__("Member Name / Code").__(":")." ".__("*")."</td>  <td><input type='text' name='code' $inputbox_style /></td> </tr> <tr>  <td>".__("Currency").__(":")." ".__("*")."</td>  <td>$currency_select</td> </tr> <tr>  <td>".__("Bank In Amount").__(":")." ".__("*")."</td>  <td><input type='text' name='amount_in' $inputbox_style /></td> </tr>
 <tr>
  <td colspan='2' class='padding_height center'><input type='submit' value=\"".__("Transact")."\" name='submit_btn' /></td>
 </tr>
</table>
</form>";

$content="<h2>$page_title</h2>$member_point";
           
print format_admin_page($content, $this_title, $jvscript);
?>